<template>
	<view class="view-contain">
		<!-- 公共组件-每个页面必须引入 -->
		<public-module :leftIcon="'arrow-left'" :title="title" />

		<!-- 积分提示条 -->
		<view class="points-notice">
			<u-icon name="info-circle" size="24" color="#FF9500"></u-icon>
			<text class="notice-text">阅读消耗2积分，下载附件消耗10积分，您积分：{{ user.totalPoints || 0 }}</text>
		</view>

		<!-- 自定义标签页切换 -->
		<view class="custom-tabs">
			<view v-for="(item, index) in tabList" :key="index"
				:class="['tab-item', currentTab === index ? 'active' : '']" @click="handleTabChange(index)">
				{{ item.name }}
			</view>
		</view>

		<!-- 文章列表 -->
		<mescroll-uni :height="`${height}px`" :down="downOption" :up="upOption" @init="mescrollInit"
			@down="downCallback" @up="upCallback">
			<view class="article-list">
				<view class="article-item" v-for="(item, index) in articleList" :key="item.id"
					@click="toDetail(item.content,item)">
					<view class="article-index">{{ index + 1 }}</view>
					<view class="article-content">
						<view class="article-title">{{ item.title }}</view>
						<!-- 第一行信息：分类、日期、浏览量 -->
						<view class="article-info first-line">
							<view class="info-item">
								<u-icon name="tags" size="14" color="#666"></u-icon>
								<text>{{ item.categoryName || (channelId === 0 ? '上岸经验' : '苏榜原创') }}</text>
							</view>
							<view class="info-item">
								<u-icon name="clock" size="14" color="#666"></u-icon>
								<text>{{ formatDate(item.createTime) }}</text>
							</view>
							<view class="info-item">
								<u-icon name="eye" size="14" color="#666"></u-icon>
								<text>{{ item.views || 0 }}次浏览</text>
							</view>
						</view>
						<!-- 第二行信息：积分和附件提示 -->
						<view class="article-info second-line">
							<!-- 积分消耗提示 -->
							<view class="info-item points-item">
								<u-icon name="bookmark" size="14" color="#FF9500"></u-icon>
								<text>阅读: 2积分</text>
							</view>
							<!-- 附件提示 -->
							<view v-if="item.attachment" class="info-item attachment-item">
								<u-icon name="file-text" size="14" color="#2196F3"></u-icon>
								<text>附件: 下载10积分</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</mescroll-uni>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import {
		articleList,
		articleDetail,
		downloadAttachment
	} from "@/config/api.js";

	export default {
		mixins: [MescrollMixin], // 使用mixin  
		data() {
			return {
				height: 0,
				channelId: 0, // 0:上岸经验 5:苏榜原创
				currentTab: 0,
				tabList: [{
						name: '最新文章',
						orderBy: 'createTime'
					},
					{
						name: '最多查看',
						orderBy: 'viewCount'
					},
					{
						name: '推荐文章',
						isRecommend: 1
					},
					{
						name: '我的收藏',
						myCollect: 1
					}
				],
				articleList: [],
				total: 0,
				downOption: {
					use: true
				},
				upOption: {
					textNoMore: '没有更多了~',
					toTop: {
						right: '24rpx',
						bottom: '60rpx'
					}
				}
			};
		},
		computed: {
			...mapState(['user', 'loginSuccess']) ,
			title() {
				return this.channelId === 0 ? '上岸经验' : '苏榜原创';
			}
		},
		watch: {
			loginSuccess(newValue) {
				if (newValue) {
					this.mescroll.resetUpScroll(); // 刷新页面数据
					this.$store.commit('setLoginSuccess', false); // 重置登录成功状态
				}
			}
		},
		onLoad(option) {
			if (option.channelId) {
				this.channelId = Number(option.channelId);
			}
		},
		onReady() {
			this.$nextTick(() => {
				const res = uni.getWindowInfo();
				// 44px公共顶部导航栏 + 积分提示条 + 标签页切换栏
				const query = uni.createSelectorQuery().in(this);
				query.select('.points-notice').boundingClientRect();
				query.select('.custom-tabs').boundingClientRect();
				query.exec((rects) => {
					const noticeHeight = rects[0]?.height || 0;
					const tabsHeight = rects[1]?.height || 0;
					this.height = res.windowHeight - 44 - noticeHeight - tabsHeight;
				});
			});
		},
		methods: {
			...mapMutations(['emptyUserInfo']),
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				// iOS兼容的日期解析
				const isoString = dateStr.replace(' ', 'T');
				const date = new Date(isoString);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
			},

			// 标签切换
			async handleTabChange(index) {
				if (index < 0 || index >= this.tabList.length) return;

				// 立即更新当前标签
				this.currentTab = index;

				// 清空文章列表
				this.articleList = [];

				// 构造请求参数
				const currentTab = this.tabList[this.currentTab];
				let params = `?pageNum=1&pageSize=10&channelId=${this.channelId}`;

				// 根据当前标签配置添加参数
				if (currentTab.orderBy) {
					params += `&orderBy=${currentTab.orderBy}`;
				}
				if (currentTab.isRecommend) {
					params += '&isRecommend=1';
				}
				if (currentTab.myCollect) {
					if (!this.user.userId) {
						// 静默登录机制，直接跳转到首页
						uni.reLaunch({
							url: '/pages/index/index'
						});
						return;
					}
					params += '&myCollect=1';
				}

				// 重置滚动并触发数据加载
				await this.$nextTick();
				if (this.mescroll) {
					this.mescroll.resetUpScroll(false);
				}
			},

			// 跳转到详情页
			async toDetail(content, item) {
				// 检查用户是否登录
				if (!this.user.userId) {
					// 静默登录机制，直接跳转到首页
					uni.reLaunch({
						url: '/pages/index/index'
					});
					return;
				}
				
				// 检查积分是否充足（阅读需要2积分）
				if ((this.user.totalPoints || 0) < 2) {
					uni.$u.toast('您的积分不足，无法阅读文章（需要2积分）');
					return;
				}
				
				// 二次确认是否消耗积分阅读
				uni.showModal({
					title: '积分提示',
					content: `阅读本文将消耗2积分，${item.attachment ? '本文包含附件，下载需额外消耗10积分' : ''}是否继续？`,
					confirmText: '确认阅读',
					cancelText: '取消',
					success: async (res) => {
						if (res.confirm) {
							try {
								// 调用articleDetail扣除阅读积分(2积分)并更新浏览量
								const res = await articleDetail(item.id);

								if (res.code === 200) {
									// 更新成功后，跳转到详情页
									uni.navigateTo({
										url: `/pages/articles/components/detail?content=${encodeURIComponent(content)}&attachment=${item.attachment}&id=${item.id}&channelId=${item.channelId}`
									});
								} else {
									uni.$u.toast(res.msg || '获取文章详情失败');
								}
							} catch (error) {
								this.mescroll.endErr(); // 结束加载并显示错误
								console.error('获取文章详情失败:', error);
								uni.$u.toast('获取文章详情失败，请检查网络');
							}
						}
					}
				});
			},

			// 上拉加载
			async upCallback(page) {
				try {
					const currentTab = this.tabList[this.currentTab];
					let params = `?pageNum=${page.num}&pageSize=${page.size}&channelId=${this.channelId}`;

					// 根据当前标签配置添加参数
					if (currentTab.orderBy) {
						params += `&orderBy=${currentTab.orderBy}`;
					}
					if (currentTab.isRecommend) {
						params += '&isRecommend=1';
					}
					if (currentTab.myCollect) {
						params += '&myCollect=1';
					}


					const res = await articleList(params);
					if (res && res.rows) {
						this.total = res.total;
						this.mescroll.endBySize(res.rows?.length || 0, res.total);
						if (page.num == 1) this.articleList = [];
						this.articleList = this.articleList.concat(res.rows);
					}
				} catch (error) {
					this.mescroll.endErr();
					uni.$u.toast('获取文章列表失败，请检查网络');
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.view-contain {
		display: flex;
		flex-direction: column;
		background-color: #F5F6F5;
		min-height: 100vh;
	}

	// 积分提示条样式
	.points-notice {
		display: flex;
		align-items: center;
		background-color: #FFF8E6;
		padding: 16rpx 20rpx;
		font-size: 26rpx;
		color: #E67E22;
		border-bottom: 1px solid #FFE0B2;
		
		.notice-text {
			margin-left: 10rpx;
			line-height: 1.4;
		}
	}

	.custom-tabs {
		display: flex;
		background-color: #FFFFFF;
		padding: 0 20rpx;
		border-bottom: 1px solid #eee;

		.tab-item {
			position: relative;
			padding: 24rpx 32rpx;
			font-size: 28rpx;
			color: #666;
			transition: all 0.3s;

			&.active {
				color: #409EFF;
				font-weight: 500;

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background-color: #409EFF;
					border-radius: 2rpx;
				}
			}
		}
	}

	.article-list {
		padding: 20rpx;
		width: 100%;

		.article-item {
			display: flex;
			align-items: flex-start;
			background-color: #FFFFFF;
			padding: 24rpx;
			margin-bottom: 20rpx;
			border-radius: 12rpx;

			.article-index {
				width: 40rpx;
				height: 40rpx;
				background-color: #409EFF;
				color: #FFFFFF;
				border-radius: 50%;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 24rpx;
				margin-right: 20rpx;
				flex-shrink: 0;
			}

			.article-content {
				flex: 1;

				.article-title {
					font-size: 30rpx;
					color: #333;
					font-weight: 500;
					line-height: 1.4;
					margin-bottom: 16rpx;
				}

				.article-info {
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					gap: 20rpx;
					margin-bottom: 8rpx; // 两行之间的间距
					
					// 第一行信息底部增加分隔线
					&.first-line {
						padding-bottom: 8rpx;
						border-bottom: 1px dashed #f0f0f0;
					}

					.info-item {
						display: flex;
						align-items: center;
						font-size: 24rpx;
						color: #666;

						u-icon {
							margin-right: 6rpx;
						}
					}
					
					// 积分项样式
					.points-item {
						color: #FF9500;
					}
					
					// 附件项样式
					.attachment-item {
						color: #2196F3;
					}
				}
			}
		}
	}

	.no-data {
		padding: 100rpx 0;
	}
</style>
